#!/usr/bin/python2.6

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import string
import ctypes
import urllib
import datetime
import sys

PORT = 10027
DST_PATH = '/home/aaron/workspace/hiseg/data/dst/'

lib = ctypes.CDLL("/usr/local/lib/libhiseg.so")
inf = open("./in.log", 'a+')
outf = open("./out.log", 'a+')
ret = lib.init("/home/aaron/workspace/hiseg/clasdict/")
if ret < 0 : 
	print "load dict failed ", ret
	exit(1)

class MyHandler(BaseHTTPRequestHandler):
	out = ctypes.create_string_buffer(1024)
	def do_GET(self):
		try:
			pos = self.path.find("stat")
			if pos == 1:
				dst = os.path.abspath(DST_PATH)
				info = 'start'
				i = 0
				total = 0
				for f in os.listdir(dst):
					if os.path.isdir(DST_PATH + os.sep + f) and f.isdigit():
						tail = "tail -1 "+ DST_PATH + os.sep + f + '/0'
						size = int(os.popen(tail).read())
						total += size
						if i == 0:
							info += f+"#"+str(size)
						else:
							info += "#"+f+"#"+str(size)
					else:
						continue
					i += 1 
				info += '#0'+"#"+str(total)
				info += 'end'
				self.send_response(200)
				self.send_header('Content-type',	'text/html')
				self.end_headers()
				self.wfile.write(info)
				return

			pos = self.path.find("cmd")
			if pos == 1:
				cmd = self.path[pos+len("cmd")+1:]
				cmd = urllib.unquote_plus(cmd)
				pipe = os.popen(cmd);
				self.send_response(200)
				self.send_header('Content-type',	'text/html')
				self.end_headers()
				self.wfile.write(cmd+'<br/>'+pipe.read())
				return

			f = open(os.curdir + os.sep + self.path) #self.path has /test.html
			self.send_response(200)
			self.send_header('Content-type',	'text/html')
			self.end_headers()
			self.wfile.write(f.read())
			f.close()

		except IOError:
			self.send_error(404,'File Not Found: %s' % self.path)

	def do_POST(self):
		try:
			l = string.atoi(self.headers.getheader("Content-Length"))
			if l == 0: return
			input = self.rfile.read(l)
			pos = input.find("text=")

			mode = input.find("mode=html");

			self.send_response(200)
			self.send_header('Content-type', 'text/html')
			self.end_headers()
		
			s = lib.get_segger()
			if s <= 0 : return
			input = input[pos+5:]
			input = urllib.unquote_plus(input)
			print >> inf, self.address_string(),"- - [", self.log_date_time_string(), "]\n", input
			

			start = datetime.datetime.now()
			ret = lib.hiseg_do(s, input, len(input))
			if ret < 0 : 
				lib.return_segger(s)
				return
			end = datetime.datetime.now()
			if mode != -1:
				self.wfile.write("<span class='cost'>cost:" + str((end-start).microseconds) + "us</span>\n\n")
			print >> outf, self.address_string(),"- - [", self.log_date_time_string(), "] ", "cost:" + str((end-start).microseconds) + "us"
			
			p = ctypes.addressof(self.out)
			ret = lib.hiseg_next_res(s, p, 1024)
			while ret > 0 :
				if mode != -1:
					self.wfile.write(ctypes.string_at(self.out, ret) + "<span class='sp'> | </span>")
				else:
					self.wfile.write(ctypes.string_at(self.out, ret) + " | ")
				print >> outf, ctypes.string_at(self.out, ret) + " | ",
				ret = lib.hiseg_next_res(s, p, 1024)
			self.wfile.write("\n")
			lib.return_segger(s)
			print >> outf, ""
			
		except Exception, e:
			self.send_error(404, "seg error: " + repr(e))
	def do_OPTIONS(self):
			self.send_error(404, "not support OPTIONS")

def main():
	try:
		server = HTTPServer(('', PORT), MyHandler)
		print 'Welcome to the machine...'
		server.serve_forever()
	except KeyboardInterrupt:
		print '^C received, shutting down server'
		server.socket.close()

if __name__ == '__main__':
	main()
